/*
 * Giffel, Android application
 *
 * Copyright (C) 2011  Mid Sweden University
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package se.appening;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class GeoLocHandler implements LocationListener {

    private static final int TWOMINUTES = 1000 * 60 * 2;
    private static final long MINUPDATEINTERVALMILLIS = 1000;
    private static final float UPDATEDISTANCEMETERS = 15;

    private LocationManager locService;
    private Criteria criteria = new Criteria();
    private String currentProvider;
    private Location bestLocation;

    private SubjectEvent locationChanged = new SubjectEvent("GeoLoc");

    public GeoLocHandler(LocationManager locationService) {
        locService = locationService;
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        currentProvider = locService.getBestProvider(criteria, true);
        locService.requestLocationUpdates(currentProvider,
                MINUPDATEINTERVALMILLIS, UPDATEDISTANCEMETERS, this);
    }

    public SubjectEvent getLocationChangedEvent() {
        return locationChanged;
    }

    public void onLocationChanged(Location location) {
        currentProvider = locService.getBestProvider(criteria, true);
        if (isBetterLocation(location, bestLocation)) {
            bestLocation = location;
            locationChanged.signalIndependent(new LocationChanged(location));
        }
    }

    public void onProviderDisabled(String provider) {
        if (provider.contentEquals(currentProvider)) {
            currentProvider = locService.getBestProvider(criteria, true);
            locService.requestLocationUpdates(currentProvider,
                    MINUPDATEINTERVALMILLIS, UPDATEDISTANCEMETERS, this);
        }
    }

    public void onProviderEnabled(String provider) {
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (weDontHaveA(currentBestLocation)) {
            return true;
        }

        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean significantlyNewer = timeDelta > TWOMINUTES;
        boolean significantlyOlder = timeDelta < -TWOMINUTES;
        boolean newerThanCurrent = timeDelta > 0;

        if (significantlyNewer) {
            return true;
        } else if (significantlyOlder) {
            return false;
        }

        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean locationIsMoreAccurate = accuracyDelta < 0;
        boolean locationIsLessAccurate = accuracyDelta > 0;
        boolean locationIsSignificantlyLessAccurate = accuracyDelta > 200;

        boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider());

        if (locationIsMoreAccurate) {
            return true;
        } else if (newerThanCurrent && !locationIsLessAccurate) {
            return true;
        } else if (newerThanCurrent && !locationIsSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }

    private boolean weDontHaveA(Location currentBestLocation) {
        return currentBestLocation == null;
    }

    private boolean isSameProvider(String provider1, String provider2) {
        return provider1 == null? provider2 == null: provider1.equals(provider2);
    }

    public Location getCurrentLocation() {
        return bestLocation;
    }

}
